package aip.ui.user.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import aip.core.model.user.User;

public class CurrentUserInitializeFilter implements Filter
{
    public final static String SESSION_USER_HOLDER = "CURRENT_USER";

    public void destroy()
    {
        UserHelper.setUser(null);
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException
    {
        try
        {
            User user = UserHelper.getUser();
            if (user == null)
            {
                user = (User) ((HttpServletRequest) request).getSession()
                        .getAttribute(SESSION_USER_HOLDER);
                if (user != null)
                {
                    UserHelper.setUser(user);
                }
            }
        }
        finally
        {
            try
            {
                chain.doFilter(request, response);
            }
            finally
            {
                UserHelper.setUser(null);
            }
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException
    {
    }

}
